package com.example.sneakerappforme1105.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.sneakerappforme1105.DTO.OrderPostData;
import com.example.sneakerappforme1105.DataProvider;
import com.example.sneakerappforme1105.GoodsDetailActivity;
import com.example.sneakerappforme1105.MainApplication;
import com.example.sneakerappforme1105.PaymentActivity;
import com.example.sneakerappforme1105.PurcharseActivity;
import com.example.sneakerappforme1105.R;
import com.example.sneakerappforme1105.ViewModel.CartViewModel;
import com.example.sneakerappforme1105.adapter.CartItemAdapter;
import com.example.sneakerappforme1105.bean.Address;
import com.example.sneakerappforme1105.bean.BackendGoods;
import com.example.sneakerappforme1105.bean.CartItem;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.bean.Order;
import com.example.sneakerappforme1105.bean.OrderItem;
import com.example.sneakerappforme1105.constant.NetConst;
import com.example.sneakerappforme1105.dao.AddressDao;
import com.example.sneakerappforme1105.dao.CartItemDao;
import com.example.sneakerappforme1105.dao.GoodsDao;
import com.example.sneakerappforme1105.dao.OrderDao;
import com.example.sneakerappforme1105.dao.OrderItemDao;
import com.example.sneakerappforme1105.util.DateUtil;
import com.example.sneakerappforme1105.util.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CartFragment extends Fragment {
    private String TAG ="CartFragment";
    private View mView;
    private AppCompatActivity mActivity;
    private TextView tv_count;
    private TextView tv_total_price;
    private LinearLayout ll_content; // 声明一个线性布局对象
    private LinearLayout ll_pay; // 声明一个购物车列表的线性布局对象
    private LinearLayout ll_empty; // 声明一个线性布局对象
    private CartItemDao cartItemDao;    // 用来查询购物车项目
    private GoodsDao goodsDao; // 用来 购物车项对应的商品
    private OrderDao orderDao; // 用来 创建订单项目
    private AddressDao addressDao; //用来查询地址
    private OrderItemDao orderItemDao;  // 插入订单项

    private Long mUserId;   // 得传入订单
    private Long mCartId; // 应该传来当前的购物车 id 进行查询 片段和片段之间的跳转
    private List<CartItem> mCartItemList = new ArrayList<>();   // 用来展示
    private List<CartItem> mSelect = new ArrayList<>();
    private HashMap<Long, Goods> mGoodsMap = new HashMap<>(); // long 是info.goodsId作为外键
    private RecyclerView rv_cart;
    private CartItemAdapter cartItemAdapter;
    private CartViewModel cartViewModel;
    private MainApplication mApp;
    private boolean datachange=false;
    private int tmpSize;
    private TextView tv_empty;

    public CartFragment() {

    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        Log.d(TAG,"CartFragment启动");
        cartItemDao = MainApplication.getInstance().getAppDatabase().cartItemDao();
        goodsDao = MainApplication.getInstance().getAppDatabase().goodsDao();
        orderDao = MainApplication.getInstance().getAppDatabase().orderDao();
        addressDao = MainApplication.getInstance().getAppDatabase().addressDao();
        orderItemDao = MainApplication.getInstance().getAppDatabase().orderItemDao();

        mActivity = (AppCompatActivity) getActivity();
        mView = inflater.inflate(R.layout.fragment_cart, container, false);
        rv_cart = mView.findViewById(R.id.rv_cart);
        LinearLayoutManager llm = new LinearLayoutManager(mActivity);
        rv_cart.setLayoutManager(llm);

        DataProvider dataProvider = (DataProvider) getActivity();   // 用来得到 所挂载活动的成员变量

        if(dataProvider!=null){
            Log.d(TAG,"dataProvider不为空");
            mUserId = dataProvider.getUserId();
            mCartId = dataProvider.getCartId();
            cartViewModel = dataProvider.getCartViewModel();    // 接收来自RootAct的ViewModel
            mCartItemList = dataProvider.getCartItemList();
            mGoodsMap = dataProvider.getGoodsMap();
            cartViewModel.setCartItemList(mCartItemList);
            cartViewModel.setGoodsMap(mGoodsMap);
        }
        Log.d(TAG,"购物车"+mCartId);



            // 最开始从活动中拿去CartViewModel
//        cartViewModel = new ViewModelProvider(mActivity).get(CartViewModel.class);
            // 现在改为从 MainApplication中拿取 CartViewModel

//        cartViewModel = MainApplication.getInstance().getCartViewModel();   // 直接从mainApplication 中拿到 CartViewModel

        // 获取 ViewModel 中保存的 LiveData
//        cartViewModel.getCartItemList().observe(getViewLifecycleOwner(), items -> {
//            mCartItemList = items != null ? items : new ArrayList<>();
//        });
//        cartViewModel.getGoodsMap().observe(getViewLifecycleOwner(), map->{
//            mGoodsMap = map !=null ? map: new HashMap<>();
//        });



        // 为 rv_cart准备数据,如果 ViewModel 没有数据，从数据库初始化
        if(mCartItemList.isEmpty()) {

            mCartItemList = cartItemDao.queryCartItemByCartId(mCartId); // 根据购物车id，查询所有的购物车项
            Log.d(TAG, "CartViewModel 从数据库中获取数据"+mCartItemList.size());

            if (mCartItemList != null) {


                cartViewModel.setCartItemList(mCartItemList);

            } else {
                mCartItemList = new ArrayList<>(); // sql查询为空,重新初始化
            }
        }

        // 初始化 itemSize
//        itemSize = mCartItemList.size();

        cartItemAdapter = new CartItemAdapter(mActivity, mCartItemList, mGoodsMap);
        cartItemAdapter.setButtonListener(new CartItemAdapter.ItemButtonListenr() {
            @Override
            public void onAddClick(View v, int position) {
                // 更新 mCartItemList

                CartItem item = mCartItemList.get(position);
                Goods goods = goodsDao.queryGoodsByGoodsId(item.getGoodsId());// 当前购物车项目对应的商品数
                if((item.getNum())<goods.getCapcity()) {
                    item.setNum(item.getNum() + 1);
                    cartViewModel.updateCartItem(item, position);    // 更新cartView中的数据


                    Log.d(TAG, "添加" + item.getNum());    // 添加成功，但是没显示.打印当前商品数量

                    cartItemAdapter.notifyDataSetChanged();
                }else{
                    ToastUtil.show(mActivity,"已经到达宝贝最大数量~");
                }
                datachange = true;
                refreshTotalPrice();
            }

            @Override
            public void onSubClick(View v, int position) {
                CartItem item = mCartItemList.get(position);
                int num = item.getNum();

                if((num-1)>0) {
                    item.setNum((num-1));
                    cartViewModel.updateCartItem(item, position);   // 更新cartViewModel
                    datachange = true;
                    mCartItemList.get(position).setNum(num - 1);
                }else{
                    ToastUtil.show(mActivity,"宝贝不能再减少了");
                }
                cartItemAdapter.notifyDataSetChanged();
                refreshTotalPrice();
            }

            @Override
            public void onSetCheckBox(View v, int position, boolean flag) {
                CartItem item = mCartItemList.get(position); // 当前选中的商品
                if(flag){   // 选中框选中
                    //当前被选中,加入被选中
                    item.setIsChecked(1);
                    cartViewModel.updateCartItem(item, position);
                    cartItemAdapter.notifyDataSetChanged();
                    refreshTotalPrice();
                }else{
                    // 取消选中
                    item.setIsChecked(0);
                    cartViewModel.updateCartItem(item, position);
                    cartItemAdapter.notifyDataSetChanged();
                    refreshTotalPrice();
                }
            }


        });

        rv_cart.setAdapter(cartItemAdapter);

        cartItemAdapter.setOnItemLongClickListener(new CartItemAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                // 长按删除
                CartItem cartItem = mCartItemList.get(position);
                // 创建对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setTitle("删除订单")
                        .setMessage("确定要删除该商品吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 点击确定后发送删除请求
                            cartItemDao.deleteOneCartItem(cartItem.getGoodsId(),cartItem.getSize());
                            mCartItemList.remove(position);
                            cartItemAdapter.notifyDataSetChanged();
                            MainApplication.goodsCount-=1;
                            showCount();    // 判断是否为空
                            refreshTotalPrice();
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                            // 点击取消，关闭对话框
                            dialog.dismiss();
                        })
                        .show();
            }
        });

        TextView tv_title = mView.findViewById(R.id.tv_title);
        tv_title.setText("购物车");
        tv_count = mView.findViewById(R.id.tv_count);
        tv_total_price = mView.findViewById(R.id.tv_total_price);
        ll_content = mView.findViewById(R.id.ll_content);
        ll_pay = mView.findViewById(R.id.ll_pay);
        ll_empty = mView.findViewById(R.id.ll_empty);
        ImageView iv_back = mView.findViewById(R.id.iv_back);
        iv_back.setVisibility(View.GONE);

        mView.findViewById(R.id.btn_shopping_channel).setOnClickListener(view -> {
            // 从购物车片段 跳转到 商品页面片段
            ViewPager vp_content = mActivity.findViewById(R.id.vp_content);
            if(vp_content!=null){
                vp_content.setCurrentItem(0);   // 跳转到商品页面
            }

            RadioGroup rg_tabbar = mActivity.findViewById(R.id.rg_tabbar);
            ((RadioButton)rg_tabbar.getChildAt(0)).setChecked(true);
        });

        mView.findViewById(R.id.btn_clear).setOnClickListener(view -> {
            cartItemDao.deleteAllCartItemByCartId(mCartId); // 清空数据库
            mCartItemList.clear();
            // 提示 recyclerView数据变化
            MainApplication.goodsCount = 0;
            showCount();    // 显示最新商品数量, 根据商品数量展示相应的LinearLayout
            ToastUtil.show(mActivity,"购物车已清空");
            datachange = true;
            refreshTotalPrice();
        });

        mView.findViewById(R.id.btn_settle).setOnClickListener(view -> {

            // 结算接口
            // 创建订单 未支付
            double total = Double.parseDouble(tv_total_price.getText().toString());



            Log.d(TAG,"mGoodsMap大小为"+mGoodsMap.size());
            // 序列化数据
            List<Address> addressList = addressDao.getAllAddressesByUserId(mUserId);
            if (total!=0) {
                if(addressList.size()!=0) {
                    Intent intent = new Intent(mActivity, PurcharseActivity.class);
                    intent.putExtra("userId", mUserId);
                    intent.putExtra("cartId", mCartId);
                    intent.putExtra("total", total);
                    intent.putExtra("fromCart", true);

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("goodsMap", mGoodsMap);
                    bundle.putSerializable("cartItemList", new ArrayList<>(mCartItemList));
                    intent.putExtras(bundle);


                    startActivity(intent);
                    }else{  // 地址为0
                    ToastUtil.show(mActivity,"收货地址为空，不能下单哦~");
                    }
                }else{
                ToastUtil.show(mActivity,"选中商品为空，不能下单哦~");
            }
            });









        MainApplication.goodsCount = mCartItemList.size();  // 片段初始化的商品数
        showCount();
        refreshTotalPrice();
        return mView;
    }




    private void showCount(){
        tv_count.setText("" + MainApplication.goodsCount);
        if(mCartItemList.size()==0){
            // 购物车项 的 数量为0
            ll_content.setVisibility(View.GONE);
            ll_pay.setVisibility(View.GONE);
            ll_empty.setVisibility(View.VISIBLE);
        }else{
            ll_content.setVisibility(View.VISIBLE);
            ll_pay.setVisibility(View.VISIBLE);
            ll_empty.setVisibility(View.GONE);
        }
    }


    private void refresh() {
        cartViewModel = MainApplication.getInstance().getCartViewModel();
        // 为 rv_cart准备数据
        // 获取 ViewModel 中保存的 LiveData, 这里有问题， 如果继续新增商品不显示
        cartViewModel.getCartItemList().observe(getViewLifecycleOwner(), items -> {
            mCartItemList = items != null ? items : new ArrayList<>();
        });
        cartViewModel.getGoodsMap().observe(getViewLifecycleOwner(), map->{
            mGoodsMap = map !=null ? map: new HashMap<>();
        });

        if(mCartItemList.isEmpty()) {
            mCartItemList = cartItemDao.queryCartItemByCartId(mCartId); // 根据购物车id，查询所有的购物车项
            if (mCartItemList != null) {
                cartViewModel.setCartItemList(mCartItemList);
            } else {
                mCartItemList = new ArrayList<>(); // sql查询为空,重新初始化
            }
        }

        cartItemAdapter.updateData(mCartItemList, mGoodsMap);

        showCount();
        refreshTotalPrice();    // 设置总价格

    }



    private void refreshTotalPrice(){
        int total_price = 0;
        for(CartItem item: mCartItemList) {
            if (item.getIsChecked()==1) {
                Goods goods = mGoodsMap.get(item.getGoodsId());
                total_price += goods.getPrice() * item.getNum(); // 购物车信息有数量
            }
        }
        tv_total_price.setText("" + total_price);
    }


    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG,"重启片段");
        refresh();  // 设置片段
        showCount();
        refreshTotalPrice();

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG,"CartFragment暂停，执行更新数据库");

        List<CartItem> items = cartViewModel.getCartItemList().getValue();
        cartItemDao.deleteAllCartItemByCartId(mCartId); // 先删除再插入
        if(items.size()!=0) {    // 说明此时

            for (int i=0;i<items.size();i++) {  // 11.16 不带主键的重新插入
                CartItem item = items.get(i);
                item.setCartItemId(i+1);  // 设置主键再插入
                Log.d(TAG,"当前GoodsId"+item.getGoodsId());
                Log.d(TAG,"当前CartId" + item.getCartId());
                cartItemDao.insertOneCartItem(item);
            }

            Log.d(TAG,"结束插入数据 "+items.size());
        }



    }

    @Override
    public void onDestroyView() {   // 销毁视图时，保存购物车的数据
        super.onDestroyView();
        Log.d(TAG,"购物车片段被销毁");
        // 保存购物车数据到数据库, 保存购物车项目，下次打开时保持更新后的数据
        List<CartItem> items = cartViewModel.getCartItemList().getValue();
        if (items != null) {
            for (CartItem item : items) {
                cartItemDao.updateCart(item);
            }
        }
    }




    public void postOrderToBackend(OrderPostData postData) {

        Gson gson = new Gson();
        String postDataJson = gson.toJson(postData);

        OkHttpClient client = new OkHttpClient();
        System.out.println("提交订单到后台");

        RequestBody body = RequestBody.create(
                postDataJson,
                MediaType.parse("application/json; charset=utf-8")
        );


        Request request = new Request.Builder()
                .url("http://172.20.10.12:8080/order")
                .post(body)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 请求失败处理
                e.printStackTrace();
                System.err.println("订单上传失败: " + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 请求成功
                    String responseBody = response.body().string();
                    System.out.println("订单上传成功，返回数据: " + responseBody);
                } else {
                    // 请求失败
                    System.err.println("订单上传失败，HTTP 状态码: " + response.code());
                }
            }
        });

    }











}
